package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.api.HuanXinApi;
import com.tanhua.dubbo.enums.HuanXinMessageType;
import com.tanhua.dubbo.huanxin.config.HuanXinConfig;
import com.tanhua.dubbo.huanxin.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.huanxin.service.RequestService;
import com.tanhua.dubbo.huanxin.service.TokenService;
import com.tanhua.dubbo.pojo.HuanXinUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

@DubboService(version = "1.0.0")
@Slf4j
public class HuanXinApiImpl implements HuanXinApi {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

    /**
     * 获取环信token（获取管理员权限）
     *
     * @return
     */
    @Override
    public String getToken() {
        return this.tokenService.getToken();
    }

    /**
     * 注册环信用户
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Boolean register(Long userId) {
        ///{org_name}/{app_name}/users
        String url = StrUtil.format("{}/{}/{}/users",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName());

        HashMap<String, String> param = new HashMap<>();
        param.put("username", "HX_" + userId);
        param.put("password", IdUtil.simpleUUID());
        param.put("nickname", "HX_" + userId);
        String jsonStr = JSONUtil.toJsonStr(param);

        boolean isOk = this.requestService.execute(url, jsonStr, Method.POST).isOk();
        if (isOk) {
            //保存数据到MySQL
            HuanXinUser huanXinUser = new HuanXinUser();
            huanXinUser.setUserId(userId);
            huanXinUser.setUsername(param.get("username"));
            huanXinUser.setPassword(param.get("password"));
            huanXinUser.setNickname(huanXinUser.getUsername());
            huanXinUser.setCreated(new Date());
            huanXinUser.setUpdated(huanXinUser.getCreated());
            //TODO 如果失败，需要删除环信中的用户
            return this.huanXinUserMapper.insert(huanXinUser) == 1;
        }
        return false;
    }

    /**
     * 根据用户Id查询环信账户信息
     *
     * @param userId
     * @return
     */
    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * 根据环信用户名查询用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public HuanXinUser queryUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userName);
        return this.huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * 添加好友（双向好友关系）
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E6%B7%BB%E5%8A%A0%E5%A5%BD%E5%8F%8B
     *
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        ///{org_name}/{app_name}/users/{owner_username}/contacts/users/{friend_username}
        String url = StrUtil.format("{}/{}/{}/users/{}/contacts/users/{}",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName(),
                "HX_" + userId,
                "HX_" + friendId);
        HttpResponse response = this.requestService.execute(url, null, Method.POST);
        if (response.isOk()) {
            return true;
        }
        if (response.getStatus() == 404) {
            log.error("添加好友关系到环信失败，IM用户不存在 userId = {}, friendId = {}", userId, friendId);
        }
        return false;
    }

    /**
     * 删除好友关系（双向删除）
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E7%A7%BB%E9%99%A4%E5%A5%BD%E5%8F%8B
     *
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        ///{org_name}/{app_name}/users/{owner_username}/contacts/users/{friend_username}
        String url = StrUtil.format("{}/{}/{}/users/{}/contacts/users/{}",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName(),
                "HX_" + userId,
                "HX_" + friendId);
        HttpResponse response = this.requestService.execute(url, null, Method.DELETE);
        if (response.isOk()) {
            return true;
        }
        if (response.getStatus() == 404) {
            log.error("删除环信的好友关系失败，IM用户不存在 userId = {}, friendId = {}", userId, friendId);
        }
        return false;
    }

    /**
     * 以管理员身份发送消息
     * 文档地址：http://docs-im.easemob.com/im/server/basics/messages#%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF
     *
     * @param targetUserName     发送目标的用户名
     * @param huanXinMessageType 消息类型
     * @param msg
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        // //{org_name}/{app_name}/messages
        String url = StrUtil.format("{}/{}/{}/messages",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName());

        HashMap<String, Object> map = new HashMap<>();
        map.put("target_type", "users");
        map.put("target", Arrays.asList(targetUserName));

        HashMap<String, Object> msgMap = new HashMap<>();
        msgMap.put("type", huanXinMessageType.getType());
        msgMap.put("msg", msg);

        map.put("msg", msgMap);
        map.put("from", "admin");

        HttpResponse response = this.requestService.execute(url, JSONUtil.toJsonStr(map), Method.POST);
        if (response.isOk()) {
            return true;
        }
        if (response.getStatus() == 400) {
            log.error("发送给环信的消息结构有误！ userName = {}, msg = {}", targetUserName, msg);
        }
        return false;
    }
}
